package tt.srvinst4;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

@RestController
public class RocketMqController {
    @RequestMapping("/sendMsgSync")
    public Object sendMsgSync() {
        DefaultMQProducer producer = new DefaultMQProducer("group_name_jl");
        producer.setNamesrvAddr("localhost:9876");
        try {
            producer.start();
            for (int i = 0; i < 100; i++) {
                Message msg = new Message("JLTEST", "TAG_001", ("HELLO" + i)
                        .getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult result = producer.send(msg);
            }
        } catch (MQClientException |
                UnsupportedEncodingException |
                InterruptedException |
                RemotingException |
                MQBrokerException e) {
            e.printStackTrace();
        }

        return "OK";
    }

    @RequestMapping("/sendMsgAsync")
    public String sendMsgAsync() {
        DefaultMQProducer producer = new DefaultMQProducer("group_name_jl");
        producer.setNamesrvAddr("localhost:9876");
        try {
            producer.start();
            for (int i = 0; i < 100; i++) {
                final int index = 1;
                Message msg = new Message("JLTEST1", "TAG_002", ("Hello+" + i)
                        .getBytes(RemotingHelper.DEFAULT_CHARSET));
                producer.send(msg, new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        System.out.printf("%-10d OK %s %n", index, sendResult.getMsgId());
                    }

                    @Override
                    public void onException(Throwable e) {
                        System.out.printf("%-10d Exception %s %n", index, e);
                        e.printStackTrace();
                    }
                });
            }
        } catch (MQClientException
                | UnsupportedEncodingException
                | RemotingException
                | InterruptedException e) {
            e.printStackTrace();
        }
        return "OK";
    }
    @RequestMapping("/sendMsgOneWay")
    public String sendMsgOneWay() {

        return "OK";
    }
}
